package main

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"go.uber.org/zap"
	"service/goods_srv/global"
	"service/goods_srv/initialize"
	"service/goods_srv/model"
	"strconv"
)

// 将数据库中的商品数据同步到es中

func main() {
	initialize.InitLogger()
	initialize.InnitConfig()
	initialize.InitDB()
	initialize.InitEs()
	var goodsList []*model.EsGoods
	res := global.DB.Model(model.Goods{}).Find(&goodsList)
	if res.Error != nil {
		zap.S().Fatal(res)
	}

	bulkRequest := global.EsClient.Bulk()
	for _, v := range goodsList {
		doc := elastic.NewBulkUpdateRequest().
			Index(model.EsGoods{}.GetIndexName()).
			Id(strconv.FormatInt(int64(v.ID), 10)).
			Doc(v).
			// true 无则插入, 有则更新, 设置为false时记录不存在将报错
			DocAsUpsert(true)
		bulkRequest.Add(doc)
	}
	bulkResponse, err := bulkRequest.Do(context.Background())
	if err != nil {
		return
	}
	bad := bulkResponse.Failed()
	if len(bad) > 0 {
		s, _ := json.Marshal(bad)
		//s, _ := jsoniter.MarshalToString(bad)
		zap.S().Error("部分记录更新失败: " + string(s))
	}
	zap.S().Info("商品数据同步完成")
}
